package com.tlsy.commerce.interceptor;

import com.tlsy.commerce.model.User;
import com.tlsy.commerce.utils.AppConfig;
import com.tlsy.commerce.utils.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @author Tlsy
 * @version commerce 0.0.1
 * @date 2017/4/20  16:55
 */
public class LongTimeLoggerInterceptor extends HandlerInterceptorAdapter {
    private static final String ATTR_CONTROLLER_EXCUTION_START_TIME = "ControllerExcutionStartTime";
    private static final int EXECUTION_TIME_FOR_LOGGING = 500;
    private final Logger logger = LoggerFactory.getLogger(LongTimeLoggerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        request.setAttribute(ATTR_CONTROLLER_EXCUTION_START_TIME, System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        String handleName;
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            handleName =  handlerMethod.getShortLogMessage();
        }else{
            handleName = handler.getClass().getName();
        }

        long startTime = (long)request.getAttribute(ATTR_CONTROLLER_EXCUTION_START_TIME);
        long costTime = System.currentTimeMillis()- startTime;
        if(costTime>EXECUTION_TIME_FOR_LOGGING){

            StringBuffer logMsg = new StringBuffer();
            logMsg.append("Controller执行时间过长，耗时:").append(costTime).append("ms, ");
            logMsg.append("调用方法:").append(handleName).append("\n");
            User user = (User) ShiroUtil.getSubject().getSession().getAttribute(AppConfig.USER_SESSION);
            if(user != null){
                logMsg.append("User Id:").append(user.getId()).append(", User name:").append(user.getName()).append("\n");
            }
            logMsg.append("URL:").append(request.getRequestURL()).append("\n");
            Enumeration<String> headerNames = request.getHeaderNames();
            while(headerNames.hasMoreElements()){
                String header = headerNames.nextElement();
                logMsg.append("Header name:").append(header).append(", value:").append(request.getHeader(header)).append("\n");
            }
            Enumeration<String> params = request.getParameterNames();
            while(params.hasMoreElements()){
                String param = params.nextElement();
                logMsg.append("Param name:").append(param).append(", value:").append(request.getParameter(param)).append("\n");
            }
            logger.warn(logMsg.toString());

        }
    }
}
